package com.company.core.exception;

import com.company.core.result.Result;
import com.company.core.result.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lcl
 * @Title: ExceptionHandler
 * @ProjectName smart-planet
 * @Description: 统一异常处理
 *               源码分析入口 ：import org.springframework.web.servlet.HandlerExceptionResolver;
 * @date 18/9/22下午1:44
 */
@RestControllerAdvice
public class DealExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(DealExceptionHandler.class);

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        writeLog("数据库中已存在该记录", e);
        return ResultUtil.error("数据库中已存在该记录");
    }

    @ExceptionHandler
    public Result handleBizException(BizException e) {
        writeLog("BizException", e);
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler
    public Result handleValidatorArgsException(ValidatorArgsException e) {
        writeLog("ValidatorArgsException", e);
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler
    public Result handleException(Exception e) {
        LOGGER.error("系统发生异常:", e);
        writeLog("handleException", e);
        return ResultUtil.error();
    }

    private void writeLog(String errorType, Exception e) {
        LOGGER.info(errorType + ":{}", e.getMessage());
    }
}
